import 'package:flutter/material.dart';
import 'package:qx_global_ads/qx_global_ads.dart';
import 'package:url_launcher/url_launcher.dart';
import 'ad_fetcher.dart';





class BannerWidget extends StatefulWidget {
  final double width;
  final double height;
  final AdType type;
  final String? zoneId;

  const BannerWidget({
    super.key,
    required this.width,
    required this.height,
    required this.type,
    this.zoneId,
  });

  @override
  State<BannerWidget> createState() => _BannerWidgetState();
}

class _BannerWidgetState extends State<BannerWidget> {
  bool isLoading = true; // 控制是否正在加载
  bool isFailed = false; // 控制网络请求是否失败
  bool hasLogged = false; // 避免重复调用 logUrl
  Map<String, dynamic>? selectedBanner;

  @override
  void initState() {
    super.initState();
    _loadBanner();
  }

  // 发送 `logUrl` 请求
  Future<void> _sendLog() async {
    if (hasLogged || selectedBanner == null) return;
    final logUrl = selectedBanner!['logUrl'];
    if (logUrl != null) {
        await AdFetcher.logUrl(logUrl);
        hasLogged = true; // 避免重复发送
    }
  }

  // 加载广告
  Future<void> _loadBanner() async {
    try {
      List<dynamic> banners = await AdFetcher.fetchAds(widget.type, zoneId: widget.zoneId);
      selectedBanner = _selectBestBanner(banners);
      setState(() {
        isLoading = false;
        isFailed = false; // 请求成功
      });
    } catch (e) {
      debugPrint('Failed to fetch banners: $e');
      setState(() {
        isLoading = false;
        isFailed = true; // 请求失败
      });
    }
  }

  // 选择最合适的 Banner，根据宽高比
  Map<String, dynamic> _selectBestBanner(List<dynamic> banners) {
    double targetAspectRatio = widget.width / widget.height;
    double closestAspectRatioDiff = double.infinity;
    Map<String, dynamic> bestBanner = banners.first;

    for (var banner in banners) {
      double bannerWidth = double.parse(banner['width'].toString());
      double bannerHeight = double.parse(banner['height'].toString());
      double bannerAspectRatio = bannerWidth / bannerHeight;

      double aspectRatioDiff = (bannerAspectRatio - targetAspectRatio).abs();

      // 根据宽高比例差选出最合适的广告
      if (aspectRatioDiff < closestAspectRatioDiff) {
        closestAspectRatioDiff = aspectRatioDiff;
        bestBanner = banner;
      }
    }

    return bestBanner;
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        // 计算最终显示尺寸，如果外部无约束，才使用 widget.width / widget.height
        double displayWidth = constraints.maxWidth != double.infinity
            ? constraints.maxWidth
            : widget.width;
        double displayHeight = constraints.maxHeight != double.infinity
            ? constraints.maxHeight
            : widget.height;

        return Visibility(
          visible: !isFailed, // 如果请求失败，不显示广告
          child: isLoading
              ? const Center(child: CircularProgressIndicator()) // 加载时显示加载指示器
              : selectedBanner == null
                  ? const SizedBox.shrink() // 如果没有广告则不占用空间
                  : GestureDetector(
                      onTap: () async {
                        if (selectedBanner != null) {
                          // 点击广告跳转
                          final clickUrl = selectedBanner!['clickUrl'];
                          if (clickUrl != null) {
                            debugPrint("Clicked on banner: $clickUrl");
                            final Uri uri = Uri.parse(clickUrl);
                            await launchUrl(uri);
                          }
                        }
                      },
                      child: SizedBox(
                        width: displayWidth, // 使用计算后的宽度
                        height: displayHeight, // 使用计算后的高度
                        child: Image.network(
                          selectedBanner!['bannerContent'],
                          fit: BoxFit.cover, // 根据容器大小调整图片显示
                          loadingBuilder: (context, child, loadingProgress) {
                            if (loadingProgress == null) {
                              // 图片加载完成，触发 logUrl
                              if (!hasLogged) {
                                _sendLog();
                              }
                              return child;
                            }
                            return const SizedBox.shrink(); // 加载时显示
                          },
                          errorBuilder: (context, error, stackTrace) {
                            debugPrint("Image load failed: $error");
                            return const SizedBox.shrink(); // **图片加载失败，不占空间**
                          },
                        ),
                      ),
                    ),
        );
      },
    );
  }
}
